#include"Acceptor.h"
#include"Logger.h"
#include"TimeHelper.h"
using namespace wjc;
using namespace Log;
Acceptor::Acceptor(Core* core, const InetAddress& listenAddr, bool reuseport) :
	fd_(sockets::createNonblockingOrDie(listenAddr.family())),
	socket_(fd_),
	core_(core),
	channel_(new Channel(core, fd_)),
	listenning_(false)
{
	socket_.setReuseAddr(true);
	socket_.setReusePort(reuseport);
	socket_.bindAddress(listenAddr);
	channel_->setReadCallback(
		std::bind(&Acceptor::handleRead, this, std::placeholders::_1));
}

Acceptor::~Acceptor() {
	channel_->disableAll();
	channel_->remove();
}
void Acceptor::listen() {
	listenning_ = true;
	socket_.listen();
	channel_->enableReading();
}

void Acceptor::unlisten() {
	channel_->disableAll();
	listenning_ = false;
}

void Acceptor::handleRead(Timestamp tm) {
	InetAddress peerAddr;
	int num = 0;
	while (true) {
		int connfd = socket_.accept(&peerAddr);
		if (connfd > 0) {
			if (newConnectionCallback_) {
				newConnectionCallback_(connfd, peerAddr);
			}
			++num;
		}
		else
			break;
	}
}